//
//  YFWelComeViewController.swift
//  微博
//
//  Created by 余仿 on 16/4/9.
//  Copyright © 2016年 YF. All rights reserved.
//

import UIKit

import SnapKit

import SDWebImage

class YFWelComeViewController: UIViewController {


    override func loadView() {

        view = UIImageView(image: UIImage(named: "ad_background"))
    }


    lazy var iconView:UIImageView = {

        let img = UIImageView(image: UIImage(named: "avatar_default_big"))

        img.layer.cornerRadius = 45

        //请求相关的,这里是控制器,应该把请求相关代码放到ViewModel中,
        img.sd_setImageWithURL(YFViewModel.sharedViewModels.headImageURL)


        return img

    }()

    lazy var name:UILabel = {

        let nameLabel = UILabel()

        nameLabel.text = YFViewModel.sharedViewModels.userAccount?.name

        nameLabel.alpha = 0

        return nameLabel
    }()

    override func viewDidLoad() {
        super.viewDidLoad()

        setupUI()
    }

    func  setupUI(){

        view.addSubview(iconView)

        view.addSubview(name)

        iconView.snp_makeConstraints { (make) -> Void in

            make.centerX.equalTo(self.view.snp_centerX)

            make.centerY.equalTo(self.view.snp_bottom).offset(-200)

            make.width.height.equalTo(90)

        }


        name.snp_makeConstraints { (make) -> Void in

            make.centerX.equalTo(iconView.snp_centerX)

            make.top.equalTo(iconView.snp_bottom).offset(20)
        }

    }

    override func viewDidAppear(animated: Bool) {

        startAnimation()

    }


    func startAnimation(){
        //阻尼系数:弹簧效果,0-1,值越小,效果越明显
//        initialSpringVelocity:加速度?开始运动时的加速度?
        UIView.animateWithDuration(1, delay: 0, usingSpringWithDamping: 0.8, initialSpringVelocity: 5, options: [], animations: { () -> Void in

            //通过更新布局实现动画
            self.iconView.snp_updateConstraints { (make) -> Void in

                make.centerY.equalTo(self.view.snp_bottom).offset(-self.view.bounds.height + 180)
            }

            self.view.layoutIfNeeded()

            }) { (_) -> Void in

                //当头像动画执行完成,执行文字动画
                UIView.animateWithDuration(1, animations: { () -> Void in
                    self.name.alpha = 1
                    }, completion: { (_) -> Void in
                        //跳转首页(登录界面)
                        NSNotificationCenter.defaultCenter().postNotificationName(YFSwitchRootController, object: "Main")
                })
        }
    }
}
